import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpClientUtil {
	// private static Logger log = Logger.getRootLogger();

	public static HttpResponse sendRequest(CloseableHttpClient httpclient, HttpPost httpPost) {
		CloseableHttpResponse response = null;
		try {
			httpclient.execute(httpPost);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}

	public static String parseReponse(HttpResponse response) {
		HttpEntity entity = response.getEntity();
		String body = null;
		try {
			String charset = EntityUtils.getContentCharSet(entity);
			body = EntityUtils.toString(entity);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return body;
	}

	public static HttpPost postForm(String url, Map<String, String> param) {
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> nvpr = new ArrayList<NameValuePair>();
		Set<String> keySet = param.keySet();
		for (String key : keySet) {
			BasicNameValuePair bnvp = new BasicNameValuePair(key, param.get(key));
			nvpr.add(bnvp);
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvpr, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return httpPost;
	}

	public static String sslPost(String url, Map<String, String> param) {
		// CloseableHttpClient httpclient =
		// SSLUtil.createSSLClientDefaultAllowAllHostname();
		CloseableHttpClient httpclient = null;
		HttpPost httpPost = postForm(url, param);
		String body = null;
		try {
			Builder configBuilder = RequestConfig.custom();
			configBuilder.setConnectTimeout(10 * 1000);
			configBuilder.setSocketTimeout(10 * 1000);
			HttpClientBuilder clientBuilder = HttpClients.custom();
			clientBuilder.setDefaultRequestConfig(configBuilder.build());
			httpclient = clientBuilder.build();
			HttpResponse response = httpclient.execute(httpPost);
			body = parseReponse(response);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return body;
	}

	public static String post(String url, Map<String, String> param) throws Exception {
		CloseableHttpClient httpclient = null;
		HttpPost httpPost = postForm(url, param);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(30000).build();
		httpPost.setConfig(requestConfig);
		String body = null;
		try {
			Builder configBuilder = RequestConfig.custom();
			configBuilder.setConnectTimeout(10 * 1000);
			configBuilder.setSocketTimeout(10 * 1000);
			HttpClientBuilder clientBuilder = HttpClients.custom();
			clientBuilder.setDefaultRequestConfig(configBuilder.build());
			httpclient = clientBuilder.build();
			HttpResponse response = httpclient.execute(httpPost);
			body = parseReponse(response);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return body;
	}

	/**
	 * post请求
	 * 
	 * @param url
	 *            请求地址
	 * @param data
	 *            请求参数
	 * @return 返回body
	 */
	public static String post(String url, String data) {

		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);

		String body = null;
		try {
			// 构�?�最�?单的字符串数�?
			StringEntity reqEntity = new StringEntity(data, Charset.forName("utf-8"));
			// 设置类型
			reqEntity.setContentType("application/x-www-form-urlencoded");
			reqEntity.setContentEncoding("UTF-8");
			// 设置请求的数�?
			httppost.setEntity(reqEntity);
			// 执行
			HttpResponse httpresponse = httpclient.execute(httppost);
			HttpEntity entity = httpresponse.getEntity();
			body = EntityUtils.toString(entity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return body;
	}

	public static void main(String[] args) throws Exception {
		// Map<String, String> map = new HashMap<String, String>();
		// System.out.println("4465644545456");
		// map.put("appid", WeixinServiceEnvConstants.APPID);// 公众账号ID
		// map.put("sub_appid", "");// 商户�?
		// map.put("mch_id", WeixinServiceEnvConstants.MCHID);// 商户�?
		// map.put("sub_mch_id", WeixinServiceEnvConstants.sub_mch_id);// 子商户号
		// map.put("device_info", "WEB");// 设备�?
		// map.put("nonce_str", "" + UUID.randomUUID().toString().replace("-",
		// ""));// 随机字符�?
		// map.put("body", "test");// 商品描述 body
		// map.put("detail", "test");// 商品详情 detail
		// map.put("attach", "test");// 附加数据 attach
		// map.put("out_trade_no", "" + System.currentTimeMillis());// 商户订单�?
		// // out_trade_no
		// map.put("fee_type", "CNY");// 货币类型 fee_type
		// map.put("total_fee", "10");// 总金�? total_fee
		// map.put("spbill_create_ip", "127.0.0.1");// 终端IP spbill_create_ip
		// map.put("time_start", DateUtil.dateToStr(new Date(),
		// "yyyyMMddHHmmss"));// 交易起始时间
		// // time_start
		// map.put("time_expire", DateUtil.dateToStr(
		// new Date(System.currentTimeMillis() + 1000*60*30),
		// "yyyyMMddHHmmss"));// 交易结束时间 time_expire
		// map.put("goods_tag", "WXG");// 商品标记 goods_tag
		// map.put("notify_url", "http://www.weixin.qq.com/wxpay/pay.php");//
		// 通知地址
		// // notify_url
		// map.put("trade_type", "NATIVE");// 交易类型 trade_type
		// map.put("product_id", "12235413214070356458058");// 商品ID product_id
		// map.put("limit_pay", "");// 指定支付方式 limit_pay
		// map.put("openid", "");// 用户标识 openid
		// map.put("sub_openid", "");// 用户子标�?
		//
		// String signString = "";
		// Map<String, String> resultMap = CollectionUtil.sortMapByKey(map);
		// for (Map.Entry<String, String> entry : resultMap.entrySet()) {
		// if (entry.getValue() != "" && !entry.getValue().equals("")) {
		// signString += entry.getKey() + "=" + entry.getValue() + "&";
		// }
		// }
		// signString += "key=" + "e10adc3849ba56abbe56e056f20f884f";
		// System.out.println(signString);
		//
		// // resultMap.put("sign", MD5Utils.MD5(signString).toUpperCase());//签名
		// String data = MapToXMLString.converterStringMap(resultMap);
		// String siString = "<sign>" +
		// MD5andKL.md5(signString,"utf-8").toUpperCase()
		// + "</sign>\n";
		// StringBuffer sb = new StringBuffer(data);
		// sb.insert(sb.indexOf("</xml>"), siString);
		//
		// System.out.println(sb);
		// String body = HttpClientUtil
		// .post("https://api.mch.weixin.qq.com/pay/unifiedorder",
		// sb.toString());
		//
		// System.out.println(new ChangeCharset().changeCharset(body,
		// ChangeCharset.ISO_8859_1, ChangeCharset.UTF_8));
		// System.out.println(body);
		// String wxresult=XmlConver.xmltoJson(body);
		// JSONObject json=JSONObject.fromObject(wxresult);
		// System.out.println(json.getString("code_url"));
	}
}
